package com.smwish;

import java.text.SimpleDateFormat;
import java.util.Date;

public class WishUtil {

    /**
     * Return the wish time format string
     * if it is published within an hour, return "xx分钟前";
     * if it is published within a day, return "xx小时前"; 
     * if it is published within a month, return "xx天前";
     * Otherwise, return "yyyy-MM-dd";
     */	
	public static String wishDateFormat( Date date ){
    	Date now = new Date(); 
    	String timeStrFormat = "%d%s前";
    	long diff = ( now.getTime() - date.getTime() )/1000; //in seconds
    	if( diff < 60*60 ) // less than an hour
    		return String.format(timeStrFormat, diff/60, "分钟");
    	else if( diff < 60*60*24 ) // less than a day
    		return String.format(timeStrFormat, diff/(60*60), "小时");
    	else if( diff < 60*60*24*30 ) //less than a month
    		return String.format(timeStrFormat, diff/(60*60*24), "天");
    	else{
    		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
    		return fmt.format(date);
    	}
	}

	/**
	 * Parse the menu value
	 * @param menuString the input menu string
	 * @param defaultVal the default menu value
	 * @param maxVal the maximal menu value ( assuming menuVal in [0..maxVal])
	 * @return the menu value in [0..maxVal]
	 */
	public static int parseMenuVal( String menuString, int defaultVal, int maxVal ){
		if( menuString == null ) return defaultVal;
		int menuVal = defaultVal;
		try{
			menuVal = Integer.parseInt(menuString);
    	} catch( NumberFormatException ex ){
    		//ignore and keep menuVal as default
    	}
		if( menuVal >= 0 && menuVal <= maxVal )
			return menuVal;
		else
			return defaultVal;
	}
	
	/**
	 * Generate the menu in html. All are linked text except the selected menu item.
	 * An example html with selMenuVal = 0: 
	 * 		menu1 | <a href="xxx">menu2</a> | <a href="xxx">menu3</a> 
	 * @param menuList the menu list
	 * @param selMenuVal the selected menu id
	 * @param menuLinkFormat the menu link format with two parameters: menu id, menu item text
	 * @return the menu string in html
	 */
	public static String genMenuHtml( String[] menuList, int selMenuVal, String menuLinkFormat ){
		StringBuilder sb = new StringBuilder();
		for( int i = 0; i < menuList.length; i++ ){
			if( sb.length() != 0 ) sb.append(" | "); //add menu item separator
			sb.append( i == selMenuVal?  menuList[i]: //text without link for selected item 
				String.format(menuLinkFormat, i, menuList[i]) );
		}		
		return sb.toString();
	}
}
